package vip.xiaonuo.modular.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import vip.xiaonuo.modular.constant.CommonConstant;
import vip.xiaonuo.modular.entity.dto.ShipmentDTO;
import vip.xiaonuo.modular.entity.request.ActivationTruckRequest;
import vip.xiaonuo.modular.entity.request.QueryWaybillRequest;
import vip.xiaonuo.modular.entity.response.WaybillResponse;
import vip.xiaonuo.modular.entity.response.Response;
import vip.xiaonuo.modular.service.ShipmentService;
import vip.xiaonuo.modular.service.WaybillService;
import vip.xiaonuo.modular.util.CommonException;
import vip.xiaonuo.modular.util.SHA512Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author tuchaoren
 * @Date 2021-06-25
 **/
@Slf4j
@Service
public class WaybillServiceImpl implements WaybillService {

    @Value("${waybill.lspKey}")
    private String lspKey = "ac59075b964b0715";

    @Value("${waybill.lspCode}")
    private String lspCode = "rbcc_zy";

    @Value("${waybill.baseUrl}")
    private String baseUrl = "https://nnbn--uat.uat1.logwirecloud.com";

    @Value("${waybill.queryWaybillUrl}")
    private String queryWaybillUrl = "/handler/interface/adapter";

    // 激活车牌号信息
    private String activationTruckUrl = "http://39.108.3.206:9004/gps-job/cusTruck/updateTruck";

    @Autowired
    private ShipmentService shipmentService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

   /* public static void main(String[] args) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select("IFNULL(min(shipment_date),current_date() || ' 00:00:00') status");
        queryWrapper.ne("status", "90");
        QueryWaybillRequest request = new QueryWaybillRequest();
        request.setLsp_key("ac59075b964b0715");
        request.setLsp_code("rbcc_zy");
        request.setSend_time(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        request.setStart_time("2021-07-09 00:00:00");
        request.setEnd_time(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        request.setType("A");
        request.setNonce("123");
        String sign = request.getLsp_code() + request.getStart_time() + request.getEnd_time() + request.getType() + request.getSend_time();
        log.info("拼接参数 -> {}", sign);
        request.setSign(SHA512Util.SHA512(sign).toUpperCase());
        log.info("获取运单信息请求参数 -> {}", JSON.toJSONString(request));
        // 发起https请求获取运单信息
        String result = HttpRequest.post("https://nnbn--uat.uat1.logwirecloud.com" + "/handler/interface/adapter")
                .header("Content-Type", "application/json").header("protocol", "mrshipment_query").body(JSON.toJSONString(request)).execute().body();
        System.out.println(result);

    }*/
    @Override
    public WaybillResponse queryWaybill() {

        // 获取运单信息 封装请求参数
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select("IFNULL(min(shipment_date),date_format(current_date(),'%Y-%m-%d %H:%i:%S')) status");
        queryWrapper.ne("status", "90");
        queryWrapper.isNotNull("vehicle_no");
        queryWrapper.ge("shipment_date", DateUtil.format(new Date(), "yyyy-MM-dd"));
        String beginDate = shipmentService.getBaseMapper().selectOne(queryWrapper).getStatus();
        QueryWaybillRequest request = new QueryWaybillRequest();
        request.setLsp_key(lspKey);
        request.setLsp_code(lspCode);
        request.setSend_time(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        request.setStart_time(beginDate);
        request.setEnd_time(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        request.setType("A");
        request.setNonce("123");
        String sign = request.getLsp_code() + request.getStart_time() + request.getEnd_time() + request.getType() + request.getSend_time();
        log.info("拼接参数 -> {}", sign);
        request.setSign(SHA512Util.SHA512(sign).toUpperCase());
        log.info("获取运单信息请求参数 -> {}", JSON.toJSONString(request));
        // 发起https请求获取运单信息
        String result = HttpRequest.post(baseUrl + queryWaybillUrl).header("Content-Type", "application/json").header("protocol", "mrshipment_query").body(JSON.toJSONString(request)).execute().body();
        // 信息对象转换
        Response<WaybillResponse> parse = JSONObject.parseObject(result, new TypeReference<Response<WaybillResponse>>(){}.getType());
        log.info("获取到的运单信息 -> {}", JSON.toJSONString(parse.getData()));
        if (parse == null && !"200".equals(parse.getCode())) {
            throw new CommonException("获取运单信息时异常！");
        }
        WaybillResponse response = parse.getData();
//        List<ActivationTruckRequest> activationTruckRequests = new ArrayList<>();
        // 判断改车票号是否激活

        List<String> truckList = new ArrayList<>();
        if (response != null) {


            response.getShipment()
                    .stream()
                    // 过滤车牌号为空信息
                    .filter(e -> StrUtil.isNotEmpty(e.getVehicleNo()))
                    // 过滤车牌号已经激活了的信息
                    .filter(e -> !truckList.contains(e.getVehicleNo()))
                    .filter(e -> !"90".contains(e.getStatus()))
                    .forEach(e -> {
                        truckList.add(e.getVehicleNo());
                    });
        }
        stringRedisTemplate.opsForValue().set(CommonConstant.ACTIVATION_TRUCK, JSON.toJSONString(truckList));

        // 异步新增获取的运单信息
        shipmentService.batchInsertShipment(response.getShipment());
        // 返回运单信息
        return parse.getData();
    }

}
